#include "cell_bookmgr.h"
#include "ui_cell_bookmgr.h"

Cell_BookMgr::Cell_BookMgr(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Cell_BookMgr)
{
    ui->setupUi(this);

    ui->tableView->setModel(&(this->m_model));

    //设置tableView无法编辑
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //设置tableView只能选择单行
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);

    initPage();
}

Cell_BookMgr::~Cell_BookMgr()
{
    delete ui;
}

void Cell_BookMgr::initPage()
{
    this->m_model.clear();
    this->m_model.setHorizontalHeaderLabels(QStringList{"书籍ID", "书籍名称", "库存数量", "剩余数量", "一级分类", "二级分类", "三级分类", "价格", "图片"});

    QVector<QStringList> vector = SqlMgr::getInstance()->getBooks(ui->le_query->text());

    int size = vector.size();

    for(int i = 0; i < size; i++){
        QList<QStandardItem *> items;
        int cols = vector[i].size();
        for(int j = 0; j < cols; j++){
            items.append(new QStandardItem(vector[i][j]));
        }
        m_model.appendRow(items);
    }

}

int Cell_BookMgr::selectBookItem()
{
    QModelIndex modelIndex = ui->tableView->currentIndex();
    int currentRowIndex = modelIndex.row();

    qDebug() << "当前选中的行号:" << currentRowIndex;

    if(currentRowIndex < 0){
        return -1;
    }

    QStandardItem * item = this->m_model.item(currentRowIndex, 0);
    QString bookIdStr = item->text();

    qDebug() << "bookIdStr=" << bookIdStr;

    int bookId = bookIdStr.toInt();
    return bookId;
}

void Cell_BookMgr::on_btn_query_clicked()
{
    initPage();
}

void Cell_BookMgr::on_btn_add_clicked()
{
    Dlg_BookAU dlg;
    dlg.setType(-1);
    dlg.exec();
    this->initPage();
}

void Cell_BookMgr::on_btn_update_clicked()
{

    int bookId = this->selectBookItem();
    if(-1 == bookId){
        QMessageBox::warning(this, "提示", "请选中一行记录");
        return;
    }

    Dlg_BookAU dlg;
    dlg.setType(bookId);
    dlg.exec();
    this->initPage();


}

void Cell_BookMgr::on_btn_delete_clicked()
{

}

void Cell_BookMgr::on_btn_return_clicked()
{

}

void Cell_BookMgr::on_btn_borrow_clicked()
{
    int bookId = this->selectBookItem();
    if(-1 == bookId){
        QMessageBox::warning(this, "提示", "请选中一行记录");
        return;
    }

    Dlg_BookGS dlg;
    dlg.setBookid(bookId);
    dlg.initBookView();
    dlg.initUserView();
    dlg.exec();
}
